package com.sh.rpc.protocol;


import com.sh.rpc.serializer.Serializer;
import com.sh.rpc.serializer.SerializerFactory;
import io.vertx.core.buffer.Buffer;

/**
 * 编码器   字节写到buffer中   然后在用序列化器序列化
 * @author sh
 */
public class ProtocolMessageEncoder {


    /**
     * 编码
     */
    public static Buffer encode(ProtocolMessage<?> protocolMessage) throws Exception {
        if ( protocolMessage==null || protocolMessage.getHeader()==null){
            return Buffer.buffer();
        }
        ProtocolMessage.Header header = protocolMessage.getHeader();
        Buffer buffer = Buffer.buffer();    // 创建一个buffer
        buffer.appendInt(header.getMagic());  // 写入魔数
        buffer.appendByte(header.getVersion());  // 写入版本号
        buffer.appendByte(header.getSerializer());  // 写入序列化器
        buffer.appendByte(header.getType());  // 写入消息类型
        buffer.appendByte(header.getStatus());  // 写入状态
        buffer.appendLong(header.getRequestId());  // 写入请求id
        // 获取序列化器
        ProtocolMessageSerializerEnum serializerEnum = ProtocolMessageSerializerEnum.getEnumByKey(header.getSerializer());
        if ( serializerEnum==null){
            throw new RuntimeException("序列化器不存在");
        }
        Serializer serializer = SerializerFactory.getInstance(serializerEnum.getValue());
        byte[] bodyBytes = serializer.serialize(protocolMessage.getBody());
        // 写入消息体长度
        buffer.appendInt(bodyBytes.length);  // 写入消息体长度
        buffer.appendBytes(bodyBytes);  // 写入消息体
        return buffer;
    }

}
